var express = require('express');
const sqlQuery = require('../../model/HGmysql')
import sqlQuery from '../../model/HGmysql'
var router = express.Router();
router.get('/administration', async(req, res) => {
    try {
        let sql = `select eamil,shijian from user`
        let result = await sqlQuery(sql)
        res.send({ code: 0, msg: result })
    } catch (error) {
        console.log(error);
    }
    
})
router.get('/ranking', async(req, res) => {
    try {
        let sql = `SELECT obj.title, obj.id, obj.like_count,@rownum := @rownum + 1 AS rownum FROM(SELECT title,like_count,id FROM article ORDER BY like_count DESC) AS obj,(SELECT @rownum := 0) r`
        let result = await sqlQuery(sql)
        let data = result.slice(0, 5)
        res.send({ code: 0, msg: data })
    } catch (error) {
        console.log(error);
    }
})
router.post('/addarticle',async(req,res)=>{
 
    let {name,content} = req.body
    let {file} = req.files
    let arr = req.body.classed.split(",")
    let class_name01 = arr[0]
    let class_name02 = arr[1]
    let class_name03 = arr[2]
  try {
     let path = `public/articleupload/` + req.files.file.md5 + Date.now() + '.jpg'
       let paths = `http://localhost:4000${path.slice(6)}`
        file.mv(path, async function(err) {
            if (err) {
                return res.status(500).send(err);
            } else {
              let sql = `insert into article(title,content,create_time,class_name01,class_name02,class_name03,pic_url) value
                (?,?,NOW(),?,?,?,?)`
                let result = await sqlQuery(sql,[name,content,class_name01,class_name02,class_name03,paths])
              res.send('ok')
            }
        });
  } catch (error) {
    console.log(error);
    
  }
})
router.get('/getarticle',async(req,res)=>{
  try {
        //获取前台传参数据
        let { currentPage, pageSize } = req.query

       let strSql = `SELECT id,title,content,class_name01,class_name02,class_name03,pic_url,visited,like_count,create_time  FROM article   limit ${(currentPage - 1) * pageSize},${pageSize}`
       let result = await sqlQuery(strSql)
            //查询数据多少条
       let strSql2 = "select count(id) as title from article"
       let result1 = await sqlQuery(strSql2)
      let  count = result1[0].title
        res.json({
            state: 200,
            count,
            result
        })

    } catch (error) {
        console.log(error);
        
    }
})
router.delete('/article/:id',async(req,res)=>{
  try {
        let { id } = req.params;
        let strSql = `delete from article where id = ${id}`;
        let result = await sqlQuery(strSql);
     res.send({ code: 0})

    } catch (error) {
        console.log(error);
        
    }
})
module.exports = router;